package com.computergames.server.server.handler;

import com.computergames.server.domain.ClientState;
import com.computergames.server.message.ErrorResponseMessage;
import com.computergames.server.message.ModeSelectionRequestMessage;
import com.computergames.server.message.ModeSelectionResponseMessage;
import com.computergames.server.service.Interface.CheckAndUpdateClientState;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class ModeSelectionRequestMessageHandler extends SimpleChannelInboundHandler<ModeSelectionRequestMessage> {
    MatchingRequestMessageHandler MATCHING_HANDLER = new MatchingRequestMessageHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ModeSelectionRequestMessage modeSelectionRequestMessage) throws Exception {
        int mode = modeSelectionRequestMessage.getMode();
        CheckAndUpdateClientState checkAndUpdateClientState = SpringUtil.getBean(CheckAndUpdateClientState.class);

        ChannelPipeline pipeline = channelHandlerContext.pipeline();
        if(mode == 0){
            checkAndUpdateClientState.updateState(channelHandlerContext.channel(), ClientState.MODE_SELECTED);
            //添加训练模式handler
            pipeline.addLast(MATCHING_HANDLER);
            channelHandlerContext.writeAndFlush(new ModeSelectionResponseMessage(true,
                    """
                            =============================================
                            \
                            请输入训练项目：
                            \
                            Gobang（五子棋）
                            \
                            Weiqi（围棋）
                            \
                            ChineseChess（象棋）
                            \
                            Landlord（斗地主）
                            \
                            =============================================
                            \s"""));
        }
        else if (mode == 1){
            checkAndUpdateClientState.updateState(channelHandlerContext.channel(), ClientState.MODE_SELECTED);
            channelHandlerContext.writeAndFlush(new ModeSelectionResponseMessage(true,
                    """
                            =============================================
                            \
                            1、小组赛
                            \
                            2、复赛
                            \
                            3、决赛
                            \
                            =============================================
                            \s"""));
        } else {
            channelHandlerContext.writeAndFlush(new ErrorResponseMessage("输入错误，请重新输入"));
        }
        pipeline.remove(this);
    }
}
